﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Web.Security;
using BF.Membership.MembershipEF;
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;
using BF.Membership.BLL;
using System.Net;
using System.IO;
using BF.Model;
using System.Reflection;
using Base.Core.UnityFactory;
using WebDataControls;
using BF.Common;
using BF.IBLL.BaseSystem;
using BF.IBLL.BaseSystem.AreaManagement;
using BF.Web.App_Code;


public class BasePage : Page
{

    //protected override void OnInit(EventArgs e)
    //{

    //    base.OnInit(e);

    //    CheckPermission();

    //}

    #region 当前用户相关信息
    /// <summary>
    /// 用户基础信息
    /// </summary>
    public BF.Model.sys_UserInfo GetSessionCurrentUserInfo
    {
        get
        {
            if (Session["CurrentUserInfo_HIP"] == null)
            {
                try
                {
                    #region 扩展写业务系统中的userinfo表
                    Isys_UserInfoBLL iBLL = IOCFactory.GetIOCResolve<Isys_UserInfoBLL>();
                    BF.Model.sys_UserInfo userInfo = iBLL.GetModelByloginname(User.Identity.Name);
                    #endregion
                    Session["CurrentUserInfo_HIP"] = userInfo;
                }
                catch
                {
                    Response.Redirect("~/Login.aspx");
                }
                return Session["CurrentUserInfo_HIP"] as BF.Model.sys_UserInfo;
            }
            else
            {
                return Session["CurrentUserInfo_HIP"] as BF.Model.sys_UserInfo;
            }
        }
    }

    #endregion

    #region 设置按钮权限
    protected override void OnPreRenderComplete(EventArgs e)
    {
        base.OnPreRenderComplete(e);
        //当前请求页URL
        string url = Request.RawUrl;
        //设置当前按钮操作的可见性
        this.SetControlsState(url);
    }
    #endregion

    #region 表单重复提交处理
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        //DateTime dt = DateTime.Now.AddSeconds(3);

        //while (DateTime.Now < dt)
        //{
        //    // do nothing; simulate a 5-second pause
        //}
        if (!this.DesignMode)
        {
            HiddenField hf = new HiddenField();
            hf.ID = "haha.lyt.token";
            string sTokenValue = String.Empty;
            if (Session["haha.lyt.token"] == null)
            {
                Session.Add("haha.lyt.token", Guid.NewGuid().ToString());
            }
            sTokenValue = Session["haha.lyt.token"].ToString();
            hf.Value = sTokenValue;
            this.Form.Controls.Add(hf);
        }

    }
    /// <summary>
    /// 表单重复提交处理，true第一次提交，false多次提交
    /// </summary>
    /// <returns>true第一次提交，false多次提交</returns>
    protected bool IsTokenValid()
    {
        bool isToken = true;
        if (Session["haha.lyt.token"] != null)
            isToken = (this.Form.FindControl("haha.lyt.token") as HiddenField).Value.Equals(Session["haha.lyt.token"].ToString());
        bool isShow = Session["haha.lyt.token"] == null;
        Session.Remove("haha.lyt.token");
        return isToken;
    }
    #endregion 表单重复提交处理

    #region 按钮操作的可见性设置

    public List<sys_Function> AllFunctions
    {
        set
        {
            Session["AllFunctions"] = value;
        }
        get
        {
            //if (Session["AllFunctions"] == null)
            //{
            Session["AllFunctions"] = GetAllFunctions();
            //}
            return Session["AllFunctions"] as List<sys_Function>;
        }
    }

    /// <summary>
    /// 获取当前用户所有可以访问的功能模块列表
    /// </summary>
    public List<sys_Function> GetAllFunctions()
    {

        Isys_PermissionBLL iBLL =
            IOCFactory.GetIOCResolve<Isys_PermissionBLL>();
        Isys_UserInfoBLL iUserInfoBLL =
            IOCFactory.GetIOCResolve<Isys_UserInfoBLL>();
        sys_UserInfo userInfo = iUserInfoBLL
            .GetModelByloginname(User.Identity.Name);

        List<sys_Function> list = iBLL
            .GetFunctionListByUserID(userInfo.gUserID.ToString());
        return list;
    }

    protected void SetControlsState(string url)
    {
        Isys_FunctionBLL iBLL =
            IOCFactory.GetIOCResolve<Isys_FunctionBLL>();
        List<sys_Function> list = this.AllFunctions;
        sys_Function model = null;
        string[] tmps = url.Split('?');
        //根据url和获取匹配的sys_Function实体model.
        var tmpList = list
            .Where(P => String.IsNullOrEmpty(P.sPath)
                ? false
                : tmps[0].ToLower().Contains(P.sPath.Split('?')[0].ToLower()));
        //没有和url相匹配的页面.
        if (tmpList.Count() == 0)
            return;
        if (tmps.Length == 1)
        {
            model = tmpList
                .Where(P => P.sPath.Split('?').Length == 1)
                .FirstOrDefault();
        }
        else
        {
            model = tmpList.Where(P => (P.sPath.Split('?').Length == 2)
                ? tmps[1].ToLower().Contains(P.sPath.Split('?')[1])
                : false)
                .FirstOrDefault();
            if (model == null)
            {
                model = tmpList
                    .Where(P => (P.sPath.Split('?').Length == 1))
                    .FirstOrDefault();
            }
        }

        if (model != null)
        {
            string[] strs = model.sPath.Split('?');
            //url有参数设置
            if (strs.Length > 1)
            {
                //当length不等或者length相等但实际url的参数不包含设置url的参数时跳出.
                if (!((strs.Length == tmps.Length) ? tmps[1].Contains(strs[1]) : false))
                    return;
            }
            //获取当前用户选择的按钮集合
            string[] itmes = list
                .Where(P => P.gParentKey == model.gKey)
                .Select(P => P.sPath)
                .ToArray();
            //获取当前用户在功能列表存在并且未选择的按钮集合
            var notCheckedItems = iBLL
                .GetList(P => P.gParentKey == model.gKey && !itmes.Contains(P.sPath))
                .Select(P => P.sPath)
                .ToArray();
            if (notCheckedItems.Length == 0)
                return;
            for (int i = 0; i < notCheckedItems.Length; i++)
            {
                notCheckedItems[i] = notCheckedItems[i].ToLower();
            }
            DisableInput(this.Page.Controls, notCheckedItems);

        }
    }
    /// <summary>
    /// 遍历控件，查看情况下无法编辑与修改
    /// </summary>
    /// <param name="partent"></param>
    protected void DisableInput(ControlCollection partent, string[] controlIDs)
    {

        foreach (System.Web.UI.Control objControl in partent)
        {
            if (objControl.HasControls())
            {
                DisableInput(objControl.Controls, controlIDs);
            }
            else
            {
                if (objControl is System.Web.UI.WebControls.Button
                    || objControl is System.Web.UI.WebControls.LinkButton
                    || objControl is System.Web.UI.WebControls.ImageButton
                    || objControl is System.Web.UI.WebControls.HyperLink)
                {
                    if (controlIDs.Contains((objControl.ID).ToString().ToLower()))
                    {
                        objControl.Visible = false;
                    }
                }
            }
        }

    }

    #endregion

    #region 信息提示框

    /// <summary>
    /// 弹出消息窗口 ,并跳转到指定页面（仅供非Ajax页面使用）
    /// </summary>
    /// <param name="msg">提示信息</param>
    /// <param name="script">待执行的脚本程序</param>
    protected void MessageBox(string msg, string script)
    {
        string ExtMsg = @"$(document).ready(function() {Ext.MessageBox.show({title: '提示',msg: '" + msg + "',buttons: {ok:'确  定'},fn:" + script + ",icon: 'ext-mb-info'});});";
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertinfo", ExtMsg, true);
    }

    /// <summary>
    /// 弹出消息窗口（仅供Ajax页面使用）
    /// </summary>
    /// <param name="msg">提示信息</param>
    /// <param name="script">待执行的脚本程序</param>
    /// <param name="control">注册的控件</param>
    protected void Messages(string msg, string script, Control control)
    {
        string ExtMsg = @"Ext.MessageBox.show({title: '提示',msg: '" + msg + "',buttons: {ok:'确  定'},fn:" + script + ",icon: 'ext-mb-info'});";
        ScriptManager.RegisterClientScriptBlock(control, this.GetType(), "click", ExtMsg, true);
    }

    /// <summary>
    /// 弹出消息窗口 
    /// </summary>
    /// <param name="msg">提示信息</param>
    /// <param name="control">注册的控件</param>
    protected void Messages(string msg, Control control)
    {
        string ExtMsg = @"Ext.MessageBox.show({title: '提示',msg: '" + msg + "',buttons: {ok:'确  定'},icon: 'ext-mb-info'});";
        ScriptManager.RegisterClientScriptBlock(control, this.GetType(), "click", ExtMsg, true);
    }

    /// <summary>
    /// 弹出消息窗口 ,并跳转到指定页面
    /// </summary>
    /// <param name="msg">提示信息</param>
    protected void Messages(string msg)
    {
        string ExtMsg = @"Ext.MessageBox.show({title: '提示',msg: '" + msg + "',buttons: {ok:'确  定'},icon: 'ext-mb-info'});";
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "click", ExtMsg, true);
    }

    #endregion

    #region 将页面转换为查看状态
    public void EnabledControls(System.Web.UI.Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            System.Web.UI.Control tmp = control.Controls[i];

            if (tmp is TextBox)
            {
                (tmp as TextBox).ReadOnly = true;
            }
            if (tmp is DropDownList)
            {
                DropDownList ddl = (tmp as DropDownList);
                ddl.Parent.Controls.AddAt(i, new TextBox()
                {
                    Text = (ddl.SelectedItem.Text == "--请选择--") ? "" : ddl.SelectedItem.Text,
                    Width = ddl.Width,
                    ReadOnly = true
                });
                ddl.Visible = false;
                i++;
            }

            if (tmp is Label)
            {
                Label lb = (tmp as Label);

                lb.Parent.Controls.AddAt(i, new TextBox()
                {
                    Text = lb.Text,
                    ReadOnly = true
                });
                lb.Visible = false;
                i++;
            }
            if (tmp is CheckBox)
            {
                CheckBox cb = (tmp as CheckBox);
                cb.Parent.Controls.AddAt(i, new CheckBox()
                {
                    Text = cb.Text,
                    Enabled = false,
                    Checked = cb.Checked

                });
                cb.Visible = false;
                i++;
            }
            else if (tmp.Controls.Count > 0)
                EnabledControls(tmp);

        }
    }
    #endregion

    public string GetString(object iteam)
    {
        if (iteam != null)
        {
            return iteam.ToString();
        }
        else
        {
            return "暂无";
        }
    }

    /// <summary>
    /// 跳转到无有权限页面。
    /// </summary>
    /// <param name="msg"></param>
    protected void GoToNoOperation(string msg)
    {
        Response.Redirect("~/Pages/common/NoOperation.aspx?msg=" + Server.UrlEncode(msg));
    }

    protected void GoToNoOperation()
    {
        GoToNoOperation("无此操作权限！");
    }

    /// <summary>
    /// 获取排序后的集合 Ordery By sCode
    /// </summary>
    /// <param name="tableCode">表编码（大类编码）根的编码为:GEN</param>
    /// <returns></returns>
    protected List<dic_Dict> GetDictList(string tableCode)
    {
        try
        {
            //Idic_DictBLL bll = IOCFactory.GetIOCResolve<Idic_DictBLL>();
            //dic_Dict model = bll.GetModel(tableCode);
            //if (model == null || model.iUse == 0)
            //    return new List<dic_Dict>();

            List<dic_Dict> modelList = UICommon.DictList.Where(p => p.sTableCode == tableCode && p.iUse != 0).OrderBy(p => p.sCode).ToList();//查询条件：表编码 sTableCode
            return modelList.OrderBy(P => P.iSort).ToList();
            //return modelList;
        }
        catch (Exception e)
        {
            throw new Exception(e.Message + " 字段：" + tableCode + " 的值为空!");
        }
    }


    #region 地区编码处理
    /// <summary>
    /// 根据地区编码取得地区名称
    /// </summary>
    /// <returns></returns>
    public string GetAreaNameByAreaCode(string areaCode)
    {
        Isys_AreaBLL iBLL = IOCFactory.GetIOCResolve<Isys_AreaBLL>();
        string AreaName = string.Empty;
        if (areaCode.Length == 6)
        {
            if (areaCode.Substring(2, 4) == "0000")//当areacode是省编码
            {
                AreaName = (iBLL.GetModelByID(areaCode) == null) ? "" : iBLL.GetModelByID(areaCode).sName;
            }
            else if (areaCode.Substring(2, 4) != "0000" && areaCode.Substring(4, 2) == "00")//当areacode是市编码
            {
                AreaName = (iBLL.GetModelByID(areaCode.Substring(0, 2) + "0000") == null) ? "" : iBLL.GetModelByID(areaCode.Substring(0, 2) + "0000").sName;
                AreaName += (iBLL.GetModelByID(areaCode) == null) ? "" : iBLL.GetModelByID(areaCode).sName;
            }
            else
            {
                AreaName = (iBLL.GetModelByID(areaCode.Substring(0, 2) + "0000") == null) ? "" : iBLL.GetModelByID(areaCode.Substring(0, 2) + "0000").sName;
                AreaName += (iBLL.GetModelByID(areaCode.Substring(0, 4) + "00") == null) ? "" : iBLL.GetModelByID(areaCode.Substring(0, 4) + "00").sName;
                AreaName += (iBLL.GetModelByID(areaCode) == null) ? "" : iBLL.GetModelByID(areaCode).sName;
            }//当areacode是县编码
        }
        else if (areaCode.Length == 9)//当areacode是镇编码
        {
            AreaName = (iBLL.GetModelByID(areaCode.Substring(0, 2) + "0000") == null) ? "" : iBLL.GetModelByID(areaCode.Substring(0, 2) + "0000").sName; //iBLL.GetModelByID(areaCode.Substring(0, 2) + "0000").sName;
            AreaName += (iBLL.GetModelByID(areaCode.Substring(0, 4) + "00") == null) ? "" : iBLL.GetModelByID(areaCode.Substring(0, 4) + "00").sName;
            AreaName += ((iBLL.GetModelByID(areaCode.Substring(0, 6)) == null) ? "" : iBLL.GetModelByID(areaCode.Substring(0, 6)).sName) + ((iBLL.GetModelByID(areaCode) == null) ? "" : iBLL.GetModelByID(areaCode).sName);
        }
        else if (areaCode.Length == 12)//当areacode是村编码
        {
            AreaName = (iBLL.GetModelByID(areaCode.Substring(0, 2) + "0000") == null) ? "" : iBLL.GetModelByID(areaCode.Substring(0, 2) + "0000").sName;
            AreaName += (iBLL.GetModelByID(areaCode.Substring(0, 4) + "00") == null) ? "" : iBLL.GetModelByID(areaCode.Substring(0, 4) + "00").sName;
            AreaName += (iBLL.GetModelByID(areaCode.Substring(0, 6)) == null) ? "" : iBLL.GetModelByID(areaCode.Substring(0, 6)).sName;
            AreaName += (iBLL.GetModelByID(areaCode.Substring(0, 9)) == null) ? "" : iBLL.GetModelByID(areaCode.Substring(0, 9)).sName;
            AreaName += (iBLL.GetModelByID(areaCode) == null) ? "" : iBLL.GetModelByID(areaCode).sName;
        }
        return AreaName;
    }

    //获取模糊查询地区编码
    public string GetStartWithAreaCode(string areaCode)
    {
        string result = String.Empty;
        if (!String.IsNullOrEmpty(areaCode))
        {
            if (areaCode.Length == 6)
            {
                if (areaCode.Substring(2, 4) == "0000")//当areacode是省编码
                {
                    result = areaCode.Substring(0, 2);
                }
                else if (areaCode.Substring(2, 4) != "0000" && areaCode.Substring(4, 2) == "00")//当areacode是市编码
                {
                    result = areaCode.Substring(0, 4);
                }
                else
                {
                    result = areaCode;
                }//当areacode是县编码
            }
            else if (areaCode.Length == 9)//当areacode是镇编码
            {
                result = areaCode;
            }
            else if (areaCode.Length == 12)//当areacode是村编码
            {
                result = areaCode;
            }
        }
        return result;
    }


    /// <summary>
    /// 根据地区获得等级
    /// </summary>
    /// <param name="areaCode"></param>
    public int GetLevelByAreaCode(string areaCode)
    {
        Isys_AreaBLL iBLL = IOCFactory.GetIOCResolve<Isys_AreaBLL>();
        return iBLL.GetLevelByAreaCode(areaCode);
    }
    #endregion


    protected const string GBBWidth = "720";//图形报表宽度
    protected const string GBBHeight = "360";//图形报表高度



    /// <summary>
    /// 根据年月得到日期
    /// </summary>
    /// <param name="year"></param>
    /// <param name="month"></param>
    /// <returns></returns>
    public string GetDays(int year, int month)
    {
        DateTime dt;
        int dayCount = 0;
        int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        string preMonthDate = DateTime.Now.Year.ToString() + "-" + (DateTime.Now.Month - 1).ToString() + "-" + DateTime.Now.Day.ToString();
        if (DateTime.TryParse(preMonthDate, out dt))
        {
            return dt.ToString("yyyy-MM-dd");
        }
        else
        {
            if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
            {
                dayCount = 29;
            }
            else
            {
                dayCount = days[month];
            }
            return new DateTime(DateTime.Now.Year, DateTime.Now.Month - 1, dayCount).ToString("yyyy-MM-dd");
        }
    }

    #region 导出生成EXCEL处理
    /// <summary> 
    /// 将一组对象导出成EXCEL 
    /// </summary> 
    /// <typeparam name="T">要导出对象的类型</typeparam> 
    /// <param name="objList">一组对象</param> 
    /// <param name="FileName">导出后的文件名</param> 
    /// <param name="columnInfo">列名信息</param> 
    public void ExExcel<T>(List<T> objList, string FileName, Dictionary<string, string> columnInfo)
    {
        if (columnInfo.Count == 0) { return; }
        if (objList.Count == 0)
        {
            ScriptManager.RegisterStartupScript(this.Page, GetType(), Guid.NewGuid().ToString(), "alert('没有查询到数据');", true);
            return;
        }
        //生成EXCEL的HTML 
        System.Text.StringBuilder excelStr = new System.Text.StringBuilder();
        excelStr.Append("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
        excelStr.Append("<tr style=\"height:50px; font-weight:bold;font-size:20pt\" align=\"center\">");
        excelStr.Append("<td colspan='" + Convert.ToString(columnInfo.Count) + "'>");
        excelStr.Append(FileName);
        excelStr.Append("</td>");
        excelStr.Append("</tr>");
        Type myType = objList[0].GetType();
        //根据反射从传递进来的属性名信息得到要显示的属性 
        List<System.Reflection.PropertyInfo> myPro = new List<System.Reflection.PropertyInfo>();
        excelStr.Append("<tr style=\"height:30px;\" align=\"center\">");
        foreach (string cName in columnInfo.Keys)
        {
            System.Reflection.PropertyInfo p = myType.GetProperty(cName);
            if (p != null)
            {
                myPro.Add(p);
                excelStr.Append("<td>");
                excelStr.Append(columnInfo[cName]);
                excelStr.Append("</td>");
            }
        }
        excelStr.Append("</tr>");
        //如果没有找到可用的属性则结束 
        if (myPro.Count == 0) { return; }
        foreach (T obj in objList)
        {
            excelStr.Append("<tr style=\"height:30px;\">");
            foreach (System.Reflection.PropertyInfo p in myPro)
            {

                if (p.PropertyType == typeof(DateTime?))
                {
                    //if (p.GetValue(obj, null) != null)
                    //{
                    //    excelStr.Append(DateTime.Parse(p.GetValue(obj, null).ToString()).ToString("yyyy-MM-dd"));
                    //}
                    excelStr.Append("<td style=\"vnd.ms-excel.numberformat:yyyy/mm/dd\" >");
                    excelStr.Append(p.GetValue(obj, null));
                }
                else
                {
                    excelStr.Append("<td style=\"vnd.ms-excel.numberformat:@\" >");
                    excelStr.Append(p.GetValue(obj, null));
                }
                excelStr.Append("</td>");
            }
            excelStr.Append("</tr>");
        }
        excelStr.Append("</table>");
        //输出EXCEL 
        System.Web.HttpResponse rs = System.Web.HttpContext.Current.Response;
        rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        rs.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName) + ".xls");
        rs.ContentType = "application/ms-excel";
        rs.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>");
        rs.Write(excelStr);
        rs.Write("</body></html>");
        //暂时没用
        //string path = Server.MapPath("~/Temp" + DateTime.Now.ToString("yyyyMMddhhmmss") + "/");
        //if (!Directory.Exists(path)) //如果文件夹不存在则创建
        //{
        //    Directory.CreateDirectory(path);
        //}
        //if (!File.Exists(path + FileName + ".xls"))
        //{
        //    File.Create(path + FileName + ".xls");
        //}

        //rs.WriteFile(path + FileName + ".xls");
        //rs.Flush();

        rs.End();
    }

    /// <summary> 
    /// 将一组对象导出成EXCEL 
    /// </summary> 
    /// <typeparam name="T">要导出对象的类型</typeparam> 
    /// <param name="objList">一组对象</param> 
    /// <param name="FileName">导出后的文件名</param> 
    /// <param name="columnInfo">列名信息</param> 
    public void ExExcel(string FileName, string sb)
    {
        //输出EXCEL 
        System.Web.HttpResponse rs = System.Web.HttpContext.Current.Response;
        rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        rs.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName) + ".xls");
        rs.ContentType = "application/ms-excel";
        rs.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>");
        rs.Write(sb);
        rs.Write("</body></html>");
        rs.End();
    }

    /// <summary> 
    /// 将一组对象导出成EXCEL，重载方法，处理多行表头
    /// </summary> 
    /// <typeparam name="T">要导出对象的类型</typeparam> 
    /// <param name="objList">一组对象</param> 
    /// <param name="FileName">导出后的文件名</param> 
    /// <param name="columnInfo">列名信息</param> 
    /// <param name="headhtml">多行表头的合并行的html</param>
    public void ExExcel<T>(List<T> objList, string FileName, Dictionary<string, string> columnInfo, string headhtml)
    {
        if (columnInfo.Count == 0) { return; }
        if (objList.Count == 0)
        {
            ScriptManager.RegisterStartupScript(this.Page, GetType(), Guid.NewGuid().ToString(), "alert('没有查询到数据');", true);
            return;
        }
        //生成EXCEL的HTML 
        System.Text.StringBuilder excelStr = new System.Text.StringBuilder();
        excelStr.Append("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
        excelStr.Append("<tr style=\"height:50px; font-weight:bold;font-size:20pt\" align=\"center\">");
        excelStr.Append("<td colspan='" + Convert.ToString(columnInfo.Count) + "'>");
        excelStr.Append(FileName);
        excelStr.Append("</td>");
        excelStr.Append("</tr>");
        Type myType = objList[0].GetType();
        //根据反射从传递进来的属性名信息得到要显示的属性 

        excelStr.Append(headhtml);

        List<System.Reflection.PropertyInfo> myPro = new List<System.Reflection.PropertyInfo>();

        foreach (string cName in columnInfo.Keys)
        {
            System.Reflection.PropertyInfo p = myType.GetProperty(cName);
            if (p != null)
            {
                myPro.Add(p);
            }
        }

        //如果没有找到可用的属性则结束 
        if (myPro.Count == 0) { return; }
        foreach (T obj in objList)
        {
            excelStr.Append("<tr style=\"height:30px;\">");
            foreach (System.Reflection.PropertyInfo p in myPro)
            {

                if (p.PropertyType == typeof(DateTime?))
                {
                    excelStr.Append("<td style=\"vnd.ms-excel.numberformat:yyyy/mm/dd\" >");
                    excelStr.Append(p.GetValue(obj, null));
                }
                else
                {
                    excelStr.Append("<td style=\"vnd.ms-excel.numberformat:@\" >");
                    excelStr.Append(p.GetValue(obj, null));
                }
                excelStr.Append("</td>");
            }
            excelStr.Append("</tr>");
        }
        excelStr.Append("</table>");
        //输出EXCEL 
        System.Web.HttpResponse rs = System.Web.HttpContext.Current.Response;
        rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        rs.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName) + ".xls");
        rs.ContentType = "application/ms-excel";
        rs.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>");
        rs.Write(excelStr);
        rs.Write("</body></html>");
        rs.End();
    }
    #endregion

    /// <summary>
    /// 传列名称，返回列索引号
    /// </summary>
    /// <param name="dcc">DataColumnCollection</param>
    /// <param name="sColumnName">列名称</param>
    /// <returns>返回列索引号,返回-1表示未找到当前列名称</returns>
    public int GetIndexByTableColumn(DataColumnCollection dcc, string sColumnName)
    {
        for (int i = 0; i < dcc.Count + 1; i++)
        {
            if (dcc[i].ColumnName == sColumnName)
            {
                return i;
            }
        }
        return -1;
    }

    /// <summary>
    /// 初始化控件年份下拉 默认当前年，前推5年为止
    /// </summary>
    /// <param name="ddl">控件</param>
    /// <param name="nullValues">是否需要“请选择”项</param>
    public void SetControlYears(DropDownList ddl, bool nullValues)
    {
        ddl.Items.Clear();
        int iYear = Convert.ToInt32(System.DateTime.Now.Year.ToString()) - 5;//获取当前年-5 
        for (int i = 0; i < 5; i++)
        {
            iYear += 1;
            ddl.Items.Add(new ListItem(iYear.ToString(), iYear.ToString()));
            if (!nullValues)
            {
                if (iYear.ToString() == System.DateTime.Now.Year.ToString())
                { ddl.Items[i].Selected = true; }
            }
        }
        if (nullValues) { ddl.Items.Insert(0, new ListItem("--请选择--", "")); }
    }
}

